package com.zjlanyun.eplus.view.report.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.zjlanyun.eplus.R;
import com.zjlanyun.eplus.network.WebApi;
import com.zjlanyun.eplus.nohttp.HttpRequest;
import com.zjlanyun.eplus.nohttp.SimpleHttpListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lecho.lib.hellocharts.listener.PieChartOnValueSelectListener;
import lecho.lib.hellocharts.model.PieChartData;
import lecho.lib.hellocharts.model.SliceValue;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.PieChartView;

import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_ACTION;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_JSON_DATA;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_PF_XVALUE;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_PF_YVALUE;
import static com.zjlanyun.eplus.view.report.UtilConstants.MODEL_ID;
import static com.zjlanyun.eplus.view.report.UtilConstants.PIE_ACTION;
import static com.zjlanyun.eplus.view.report.UtilConstants.SHOW_PIE;
import static com.zjlanyun.eplus.view.report.UtilConstants.SQL_CONDITION;

/**
 * 作者：韩笑 on 2017/6/26 0026 08:19
 * <p>
 * 作用：饼状统计图类型统计图页面
 */


public class PieFragment extends Fragment{
    private static final String TAG = "PieFragment";

    private String modelId = "";
    //柱状统计图设置
    private PieChartView chart;
    private PieChartData data;
    private boolean hasLabels = true;//是否在薄片上显示label
    private boolean hasLabelsOutside = true;//是否在薄片外显示label
    private boolean hasCenterCircle = false;//是否中间掏空一个圈
    private boolean hasLabelForSelected = false;
    //查询获得的数据list
    private List<Map<String,String>> mList ;
    public static PieFragment newInstance(String modelId,String sql) {
        Bundle args = new Bundle();
        PieFragment fragment = new PieFragment();
        args.putString(MODEL_ID, modelId);
        args.putString(SQL_CONDITION, sql);
        fragment.setArguments(args);
        return fragment;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.pei_fragment, null);
        Log.d(TAG,getArguments().getString(MODEL_ID)+"///"+getArguments().getString(SQL_CONDITION));
        initView(view);
        return view;
    }

    /**
     * 初始化
     * @param view
     */
    public void initView(View view){
        chart = (PieChartView) view.findViewById(R.id.chart);
        modelId = getArguments().getString(MODEL_ID);
        Log.d(TAG,"操作：" + PIE_ACTION + ".MODEL_ID:"+modelId);
        getData(PIE_ACTION,modelId);
    }


    /**
    *
    *@author xiao.han
    *created at 2017/6/26 0026 8:41
    */
    public void initData(){
        chart.setOnValueTouchListener(new ValueTouchListener());
        chart.setCircleFillRatio(0.7f);//设置饼图大小
        List<SliceValue> values = new ArrayList<SliceValue>();
        for (int i = 0;i < mList.size(); i++){
            int value = Integer.parseInt(mList.get(i).get(KEY_PF_YVALUE));
            SliceValue sliceValue = new SliceValue(value, ChartUtils.pickColor());
            sliceValue.setLabel(mList.get(i).get(KEY_PF_XVALUE)+":"+(int)sliceValue.getValue()+"元");//设置label
            values.add(sliceValue);
        }
        data = new PieChartData(values);
        data.setHasLabels(hasLabels);
        data.setHasLabelsOnlyForSelected(hasLabelForSelected);
        data.setHasLabelsOutside(hasLabelsOutside);
        data.setHasCenterCircle(hasCenterCircle);
        chart.setPieChartData(data);
    }
    /**
    *饼状统计图点击监听
    *@author xiao.han
    *created at 2017/6/26 0026 8:41
    */
    private class ValueTouchListener implements PieChartOnValueSelectListener {
        @Override
        public void onValueSelected(int arcIndex, SliceValue value) {
            Toast.makeText(getActivity(), mList.get(arcIndex).get(KEY_PF_XVALUE)+":￥" + value.getValue() + "元", Toast.LENGTH_SHORT).show();
        }
        @Override
        public void onValueDeselected() {
            // TODO Auto-generated method stub
        }
    }

    /**
     * 获取数据
     * @param arg0 操作
     * @param arg1 模型id
     */
    public void getData(String arg0 ,String arg1){
        mList = new ArrayList<>();
        HttpRequest client = new HttpRequest(getActivity(), WebApi.api());
        client.getRequest().add(KEY_ACTION, arg0);
        client.getRequest().add(MODEL_ID, arg1);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, com.yanzhenjie.nohttp.rest.Response<JSONObject> response) {
                super.onSucceed(what, response);
                Log.d(TAG,"返回的数据:"+response.get().toString());
                try {
                    mList = new ArrayList<Map<String, String>>();
                    JSONObject jsonObject = new JSONObject(response.get().toString());
                    JSONArray jsonArray = jsonObject.getJSONArray(KEY_JSON_DATA);
                    for (int i = 0; i < jsonArray.length(); i ++){
                        JSONObject myjsonObject = (JSONObject) jsonArray.get(i);
                        Map<String,String> map = new HashMap<String, String>();
                        map.put(KEY_PF_XVALUE,myjsonObject.optString(KEY_PF_XVALUE));
                        map.put(KEY_PF_YVALUE,myjsonObject.optString(KEY_PF_YVALUE));
                        mList.add(map);
                    }
                    mHandler.sendEmptyMessage(SHOW_PIE);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SHOW_PIE:
                    initData();
                    break;
                default:break;
            }
        }
    };
}
